/* eslint-disable no-shadow */
/**
 * 候选人，面试邀约页
 */
import React from 'react';
import {
    Form,
    Card,
    Button,
    Input,
    DatePicker,
    Checkbox,
    Select,
    Radio,
    message,
    Spin,
    Divider,
    TimePicker,
    Alert,
    Icon as AntdIcon
} from 'antd';
import { history } from 'umi'
// import { connect } from 'umi';
import { get as getPath } from 'object-path';
import moment from 'moment';
import authHelper from '@/utils/auth/helper';
import { useRequest, defaultFormatResult } from '@/hooks';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { BottomAction } from '@/components';
import pageTabUtil from '@/utils/pageTabUtil';
import { getEmployeeInfoList } from '@/services/components/userform';
import AuthComponent from '@/utils/auth/AuthComponent';
import { sameTabProps } from '@/utils/tab';
import { useInterviewWay } from '@/pages/RecruitEmail/hooks';

import { TalentInfoHead, InviteDetail, FormHeader, Icon, UploadWork } from '../components';
import { useNeedSendMail } from '../hooks';

import RevokeModal from './RevokeModal';
import {
    getCandidateInfo,
    queryRecommendPositionList,
    saveContactInterview,
    getInterviewArrangeDetail,
    updateContactInterview,
    getModifyTime,
    getProcessStatusByResumeId
} from '../service';
import { getInterviewRoundList } from '../Setting/service';
import styles from './index.less';
import { InterviewerSchedule as Schedule } from '../containers';

const { checkCode } = authHelper;
const { TextArea } = Input;
const { Option } = Select;

const CONTACT = {
    PHONE: 1,
    WX: 2,
    QQ: 3,
    EMAIL: 4,
    OTHER: 99
};

const contactWayList = [
    {
        label: '电话',
        title: '电话号码',
        value: CONTACT.PHONE
    },
    {
        label: '微信',
        title: '微信号',
        value: CONTACT.WX
    },
    {
        label: 'QQ',
        title: 'QQ号',
        value: CONTACT.QQ
    },
    {
        label: '邮箱',
        title: '邮箱地址',
        value: CONTACT.EMAIL
    },
    {
        label: '其他',
        title: '联系信息',
        value: CONTACT.OTHER
    }
];

const RESULT = {
    ACCEPT: 1,
    RECOMMEND: 2,
    OUT: 3,
    OTHER: 99
};

// 新增面试方式
const INTERVIEWWAY = {
    SITE: 1, // 现场
    VIDEO: 2, // 视频
    TEL: 3, // 电话
    WRITTEN: 4, // 笔试
    WORK: 5, // 作业
    OTHER: 99 // 其它
};
const resultTypeList = [
    {
        label: '确认面试',
        value: RESULT.ACCEPT
    },
    {
        label: '推荐到其他岗位',
        value: RESULT.RECOMMEND
    },
    {
        label: '直接淘汰',
        value: RESULT.OUT
    },
    {
        label: '其他',
        value: RESULT.OTHER
    }
];

// const interviewRoundList = [
//     {
//         label: '专业初试',
//         value: 1
//     },
//     {
//         label: '专业复试',
//         value: 2
//     },
//     {
//         label: 'HR复试',
//         value: 3
//     },
//     {
//         label: '管理复试',
//         value: 4
//     },
//     {
//         label: '其他',
//         value: 99
//     }
// ];

const interviewWayList = [
    {
        label: '现场',
        value: INTERVIEWWAY.SITE
    },
    {
        label: '视频',
        value: INTERVIEWWAY.VIDEO
    },
    {
        label: '电话',
        value: INTERVIEWWAY.TEL
    },
    {
        label: '笔试',
        value: INTERVIEWWAY.WRITTEN
    },
    {
        label: '作业',
        value: INTERVIEWWAY.WORK
    },
    {
        label: '其他',
        value: INTERVIEWWAY.OTHER
    }
];

// const Invite = ({ form, user, location }) => {
const Invite = ({ form, location }) => {
    // const { firstOrgInfo = {} } = user;
    // const { firstCompanyCode } = firstOrgInfo;
    const { query } = location;
    const { getFieldDecorator } = form;
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [contactResult, setContactResult] = React.useState(RESULT.ACCEPT);
    // 新增面试方式state
    const [interviewWayResult, setInterviewWayResult] = React.useState(INTERVIEWWAY.SITE);
    // 文件信息
    const [showFileList, setShowFileList] = React.useState([]);
    const [visible, setVisible] = React.useState(false);
    const [infoVisible, setInfoVisible] = React.useState(!!query?.type);
    const [employeeVisible, setEmployeeVisible] = React.useState(!!query?.type);
    const [currentPositionFlag, setCurrentPositionFlag] = React.useState(true);
    const [recommendDisabled, setRecommendDisabled] = React.useState([]);
    const [contactRecordDetailVO, setContactRecordDetailVO] = React.useState({});
    const [recruitInterviewHomeworkVO, setRecruitInterviewHomeworkVO] = React.useState({});
    const [arrangeDetailVO, setArrangeDetailVO] = React.useState({});

    const modalRef = React.useRef(null);
    const employeeRef = React.useRef(null);

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return !pathname.includes('edit');
    }, [location]);

    const { data: talentInfo, loading: talentLoading, run: fetchTalentDetail } = useRequest(
        () => getCandidateInfo(query.candidateId),
        {
            manual: true,
            initialData: {},
            ...defaultFormatResult
        }
    );

    const { data: info, loading, run: fetchDetail } = useRequest(
        () => getInterviewArrangeDetail({ candidateId: query.candidateId, contactId: query.contactId }),
        {
            manual: true,
            initialData: {},
            ...defaultFormatResult
        }
    );

    // const { contactRecordDetailVO, arrangeDetailVO, recruitInterviewHomeworkVO } = info;
    // console.log(getPath(recruitInterviewHomeworkVO, 'topicFileUrl', ''));

    React.useEffect(() => {
        const { contactRecordDetailVO, arrangeDetailVO, recruitInterviewHomeworkVO } = info;
        const topicFileUrl = getPath(recruitInterviewHomeworkVO, 'topicFileUrl');
        if (topicFileUrl) {
            const fileArray = JSON.parse(topicFileUrl);
            setShowFileList(
                fileArray.map(item => ({
                    uid: item.id,
                    name: item.name,
                    status: 'done',
                    url: item.url,
                    response: item.url
                }))
            );
        }
        setContactRecordDetailVO(contactRecordDetailVO);
        setArrangeDetailVO(arrangeDetailVO);
        setRecruitInterviewHomeworkVO(recruitInterviewHomeworkVO);
    }, [info]);

    // 获取面试轮次列表
    const { data: interviewRoundList, loading: roundLoading } = useRequest(getInterviewRoundList, {
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    return data?.map(item => ({
                        label: item?.interviewName || '',
                        value: item?.id || ''
                    }));
                }
                message.error(msg);
            }
            return undefined;
        }
    });

    // 岗位列表
    const { data: postList, loading: postLoading, run: fetchPostList } = useRequest(
        () => queryRecommendPositionList(query?.resumeId),
        {
            manual: true,
            initialData: [],
            ...defaultFormatResult
        }
    );

    // 搜索人员
    const { data: employeeList, run: fetchEmployeeList, mutate: setEmployeeList } = useRequest(
        tagName =>
            getEmployeeInfoList({
                // administrativeOrganizationCode: firstCompanyCode,
                name: tagName
            }),
        {
            debounceInterval: 500,
            manual: true,
            initialData: [],
            formatResult: res => {
                if (res) {
                    const { code, data, msg } = res;
                    if (code === 10000) {
                        if (!employeeRef.current) {
                            employeeRef.current = data;
                        }
                        return data;
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );

    const { data: timeList, run: fetchModifyTime } = useRequest(() => getModifyTime(query?.contactId), {
        manual: true,
        initialData: [],
        ...defaultFormatResult
    });

    // hintType 淘汰是否显示提醒框
    const { data: processStatus, run: fetchProcessStatus } = useRequest(
        () => getProcessStatusByResumeId(query?.resumeId),
        {
            manual: true,
            initialData: '',
            ...defaultFormatResult
        }
    );

    const arrangeId = arrangeDetailVO?.id;
    const resumeId = talentInfo?.recruitTalentMatcherId;

    const isNeedSendMail = useNeedSendMail({ arrangeId, resumeId });

    const handleSubmit = () => {
        form.validateFieldsAndScroll({ scroll: { alignWithTop: true } }, async (err, values) => {
            if (!err) {
                const {
                    interviewDate,
                    interviewStartTime,
                    interviewEndTime,
                    contactTime,
                    schedule,
                    currentPositionEliminateFlag,
                    deadline,
                    topicInfo,
                    ...rest
                } = values;
                const contactRecordSaveDTO = {
                    ...rest,
                    currentPositionEliminateFlag: currentPositionEliminateFlag ? 1 : 0,
                    contactTime: contactTime ? contactTime.format('YYYY-MM-DD HH:mm:00') : ''
                };

                // 面试作业
                let homeworkDTO = null;
                let arrangeSaveDTO = {};
                if (contactResult === RESULT.ACCEPT && interviewWayResult === INTERVIEWWAY.WORK) {
                    const list = showFileList.filter(m => m.status !== 'error');
                    const getTopicFileUrl = () => {
                        if (!list.length) return '';
                        return JSON.stringify(
                            list.map(item => ({
                                id: item.uid,
                                url: item.response ? item.response : item.url,
                                name: item.name
                            }))
                        );
                    };
                    homeworkDTO = {
                        deadline: deadline ? deadline.format('YYYY-MM-DD') : '',
                        topicInfo,
                        id: recruitInterviewHomeworkVO?.id,
                        topicFileUrl: getTopicFileUrl()
                    };
                    arrangeSaveDTO = {
                        ...rest,
                        candidatePresentStatus: values.candidatePresentStatus ? 1 : 0
                    };
                }

                if (contactResult === RESULT.ACCEPT && interviewWayResult !== INTERVIEWWAY.WORK) {
                    arrangeSaveDTO = {
                        ...rest,
                        interviewStartTime: `${interviewDate.format('YYYY-MM-DD')} ${interviewStartTime.format(
                            'HH:mm:00'
                        )}`,
                        interviewEndTime: `${interviewDate.format('YYYY-MM-DD')} ${interviewEndTime.format(
                            'HH:mm:00'
                        )}`,
                        candidatePresentStatus: values.candidatePresentStatus ? 1 : 0
                    };
                }

                const params = {
                    candidateId: query?.candidateId ? Number(query.candidateId) : '',
                    arrangeSaveDTO,
                    homeworkDTO
                };
                // console.log(params);
                setSubmitLoading(true);
                if (isAddPage) {
                    // console.log(
                    //     JSON.stringify({
                    //         ...params,
                    //         contactRecordSaveDTO
                    //     })
                    // );
                    saveContactInterview({
                        ...params,
                        contactRecordSaveDTO
                    })
                        .then(res => {
                            const { code, msg, data } = res;
                            if (code === 10000) {
                                // console.log(data);
                                if (values.candidateNoticeStatus && contactResult === RESULT.ACCEPT) {
                                    history.push({
                                        pathname: '/office/personnelManagement/recruitment/candidate/notice',
                                        query: {
                                            candidateId: query.candidateId,
                                            contactId: data,
                                            r: '1'
                                        },
                                        ...sameTabProps
                                    });
                                } else {
                                    pageTabUtil.goBack();
                                }
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                } else {
                    // console.log(
                    //     JSON.stringify({
                    //         candidateId: query?.candidateId ? Number(query.candidateId) : '',
                    //         ...arrangeSaveDTO,
                    //         contactId: query?.contactId ? Number(query.contactId) : ''
                    //     })
                    // );

                    updateContactInterview({
                        candidateId: query?.candidateId ? Number(query.candidateId) : '',
                        homeworkDTO,
                        ...arrangeSaveDTO,
                        contactId: query?.contactId ? Number(query.contactId) : ''
                    })
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                if (values.candidateNoticeStatus && contactResult === RESULT.ACCEPT) {
                                    history.push({
                                        pathname: '/office/personnelManagement/recruitment/candidate/notice',
                                        query: {
                                            candidateId: query.candidateId,
                                            contactId: query.contactId,
                                            r: '1'
                                        },
                                        ...sameTabProps
                                    });
                                } else {
                                    pageTabUtil.goBack();
                                }
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                }
            }
        });
    };

    React.useEffect(() => {
        fetchTalentDetail();
        if (!isAddPage) {
            fetchDetail();
            if (query?.type) {
                fetchModifyTime();
            }
        }
    }, []);

    React.useEffect(() => {
        fetchEmployeeList();
        setContactResult(getPath(contactRecordDetailVO, 'contactResult', 1));
    }, [JSON.stringify(info)]);

    React.useEffect(() => {
        const result = form.getFieldValue('contactResult');
        setContactResult(result || RESULT.ACCEPT);
        if (isAddPage && form.getFieldValue('contactDesc')) {
            form.setFieldsValue({
                contactDesc: ''
            });
        }
        if (result === RESULT.RECOMMEND && postList && postList.length === 0) {
            fetchPostList();
        }
        if (isAddPage && !processStatus && (result === RESULT.RECOMMEND || result === RESULT.OUT)) {
            fetchProcessStatus();
        }
    }, [form.getFieldValue('contactResult')]);

    const handlePositionFlagChange = React.useCallback(e => {
        setCurrentPositionFlag(e.target.checked);
    }, []);

    const renderOptions = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Option value={item.value} key={item.value}>
                    {item.label}
                </Option>
            ));
        }
        return null;
    };

    const handleEmployeeFocus = () => {
        if (employeeRef.current) {
            setEmployeeList(employeeRef.current);
        }
    };

    const handleSearch = _value => {
        fetchEmployeeList(_value.trim());
    };

    const inviteList = [
        {
            key: '联系方式',
            value: contactWayList.find(item => item.value === contactRecordDetailVO?.contactWay)?.label
        },
        {
            key: contactWayList.find(item => item.value === contactRecordDetailVO?.contactWay)?.title,
            value: contactRecordDetailVO?.contactInfo
        },
        {
            key: '联系时间',
            value: contactRecordDetailVO?.contactTime
                ? moment(contactRecordDetailVO?.contactTime).format('YYYY-MM-DD HH:mm')
                : ''
        },
        {
            key: '联系结果',
            value: resultTypeList.find(item => item.value === contactRecordDetailVO?.contactResult)?.label
        },
        {
            key: '联系内容',
            value: contactRecordDetailVO?.contactDesc
        }
    ];

    React.useEffect(() => {
        const way = form.getFieldValue('contactWay');
        if (!form.getFieldValue('contactWay')) {
            return;
        }
        if (way === CONTACT.PHONE) {
            form.setFieldsValue({
                contactInfo: getPath(talentInfo, 'talentPhone', '')
            });
        } else if (way === CONTACT.EMAIL) {
            form.setFieldsValue({
                contactInfo: getPath(talentInfo, 'talentEmail', '')
            });
        } else {
            form.setFieldsValue({
                contactInfo: ''
            });
        }
    }, [form.getFieldValue('contactWay'), JSON.stringify(talentInfo)]);

    React.useEffect(() => {
        setInterviewWayResult(form.getFieldValue('interviewWay'));
        if (form.getFieldValue('interviewWay') === INTERVIEWWAY.WORK) {
            form.setFieldsValue({ candidateNoticeStatus: 1 });
            // form.setFieldsValue({ candidatePresentStatus: 0 });
        }
    }, [form.getFieldValue('interviewWay')]);

    const handleCheck = (v, type) => {
        form.setFieldsValue({
            [type]: form.getFieldValue(type)
        });
    };

    const handleOpenChange = (v, type) => {
        if (v) {
            return;
        }
        switch (type) {
            case 'interviewStartTime':
                if (!form.getFieldValue('interviewEndTime')) {
                    form.setFieldsValue({
                        interviewEndTime: form
                            .getFieldValue('interviewStartTime')
                            ?.clone()
                            .add(1, 'hours')
                    });
                }
                break;
            case 'interviewEndTime':
                if (!form.getFieldValue('interviewStartTime')) {
                    form.setFieldsValue({
                        interviewStartTime: form
                            .getFieldValue('interviewEndTime')
                            ?.clone()
                            .subtract(1, 'hours')
                    });
                }
                break;
            default:
                break;
        }
    };

    const handleTimeClick = React.useCallback(item => {
        if (item && item.startTime && item.endTime) {
            form.setFieldsValue({
                interviewDate: moment(item.startTime),
                interviewStartTime: moment(item.startTime),
                interviewEndTime: moment(item.endTime)
            });
        }
    }, []);

    React.useEffect(() => {
        const recruitData = postList?.find(item => item.recruitId === form.getFieldValue('recommendRecruitId'));
        let arr = [];
        if (recruitData) {
            // const noticeEmployees = form.getFieldValue('noticeEmployeeCodeList') || [];
            const noticeEmployees = [];
            if (recruitData?.launchEmployeeCode) {
                noticeEmployees.push(recruitData.launchEmployeeCode);
            }
            if (recruitData?.principalEmployeeCode) {
                noticeEmployees.push(recruitData.principalEmployeeCode);
            }
            arr = [...new Set(noticeEmployees)];
            form.setFieldsValue({
                noticeEmployeeCodeList: [...new Set(noticeEmployees)].filter(item => !!item)
            });
        } else {
            arr = [];
            form.setFieldsValue({
                noticeEmployeeCodeList: undefined
            });
        }
        setRecommendDisabled(arr);
    }, [form.getFieldValue('recommendRecruitId')]);

    const getInterviewEmployees = () => {
        const tempArr = [];
        if (getPath(talentInfo, 'launchEmployeeCode')) {
            tempArr.push(getPath(talentInfo, 'launchEmployeeCode'));
        }
        if (getPath(talentInfo, 'principalEmployeeCode')) {
            tempArr.push(getPath(talentInfo, 'principalEmployeeCode'));
        }
        return [...new Set(tempArr)];
    };

    const changeAllFileList = showFileListReturn => {
        if (showFileListReturn.length <= 5) {
            setShowFileList(showFileListReturn);
        } else {
            message.error('最多只能上传五个附件');
        }
    };
    const getInterViewWorkView = () => {
        const view = (
            <>
                <Form.Item label="截止日期" required style={{ display: 'flex' }}>
                    {getFieldDecorator('deadline', {
                        initialValue: getPath(recruitInterviewHomeworkVO, 'deadline', null)
                            ? moment(getPath(recruitInterviewHomeworkVO, 'deadline', null))
                            : null,
                        rules: [
                            {
                                required: true,
                                message: '截止日期不能为空'
                            }
                        ]
                    })(<DatePicker allowClear={false} placeholder="请选择日期" style={{ width: '100%' }} />)}
                </Form.Item>
                <Form.Item label="面试题目" required style={{ display: 'flex' }}>
                    {getFieldDecorator('topicInfo', {
                        initialValue: getPath(recruitInterviewHomeworkVO, 'topicInfo', ''),
                        rules: [
                            {
                                required: true,
                                message: '面试题目不能为空'
                            }
                        ]
                    })(
                        <TextArea
                            placeholder="请输入面试题目内容"
                            autoSize={{ minRows: 10, maxRows: 20 }}
                            maxLength={2000}
                        />
                    )}
                </Form.Item>
                <Form.Item
                    label="附件"
                    vvspan={24}
                    labelCol={{ md: 4 }}
                    wrapperCol={{ md: 20 }}
                    extra=" 支持rar、zip、pdf、jpg、doc、docx、png格式的文件上传，大小为50M以内的文件。"
                >
                    <UploadWork
                        checkFileSize={50}
                        checkFileType="rar、zip、pdf、jpg、doc、docx、png"
                        fileList={showFileList}
                        setFileList={changeAllFileList}
                        checkFileTypeMsg="只能上传rar、zip、pdf、jpg、doc、docx、png格式的文件！"
                        checkFileSizeMsg="文件大小不能超过50MB！"
                    >
                        <Button style={{ marginBottom: -16 }}>
                            <AntdIcon type="upload" /> 上传文件
                        </Button>
                    </UploadWork>
                </Form.Item>
            </>
        );
        return view;
    };

    const getNotInterViewWorkView = () => {
        const view = (
            <>
                <Form.Item label="面试时间" required style={{ marginBottom: 0 }}>
                    <div style={{ display: 'flex' }}>
                        <Form.Item label="" colon={false} style={{ width: '100%', marginRight: 8 }}>
                            {getFieldDecorator('interviewDate', {
                                initialValue: getPath(arrangeDetailVO, 'interviewStartTime', '')
                                    ? moment(getPath(arrangeDetailVO, 'interviewStartTime', ''))
                                    : null,
                                rules: [
                                    {
                                        required: true,
                                        message: '面试时间不能为空'
                                    }
                                ]
                            })(<DatePicker allowClear={false} placeholder="请选择日期" style={{ width: '100%' }} />)}
                        </Form.Item>
                        <Form.Item label="" colon={false} style={{ width: '100%', marginRight: 8 }}>
                            {getFieldDecorator('interviewStartTime', {
                                initialValue: getPath(arrangeDetailVO, 'interviewStartTime', '')
                                    ? moment(getPath(arrangeDetailVO, 'interviewStartTime', ''))
                                    : null,
                                rules: [
                                    {
                                        required: true,
                                        message: '开始时间不能为空'
                                    },
                                    {
                                        validator(rule, value, callback) {
                                            const endTime = form.getFieldValue('interviewEndTime');
                                            if (value && endTime && !endTime.isAfter(value)) {
                                                callback('请选择正确的开始时间');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <TimePicker
                                    allowClear={false}
                                    minuteStep={5}
                                    disabled={!form.getFieldValue('interviewDate')}
                                    format="HH:mm"
                                    placeholder="请选择开始时间"
                                    style={{ width: '100%' }}
                                    onChange={v => handleCheck(v, 'interviewEndTime')}
                                    onOpenChange={v => handleOpenChange(v, 'interviewStartTime')}
                                />
                            )}
                        </Form.Item>
                        ~
                        <Form.Item label="" colon={false} style={{ width: '100%', marginLeft: 8 }}>
                            {getFieldDecorator('interviewEndTime', {
                                initialValue: getPath(arrangeDetailVO, 'interviewEndTime', '')
                                    ? moment(getPath(arrangeDetailVO, 'interviewEndTime', ''))
                                    : null,
                                rules: [
                                    {
                                        required: true,
                                        message: '结束时间不能为空'
                                    },
                                    {
                                        validator(rule, value, callback) {
                                            const startTime = form.getFieldValue('interviewStartTime');
                                            if (value && startTime && !startTime.isBefore(value)) {
                                                callback('请选择正确的结束时间');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <TimePicker
                                    allowClear={false}
                                    minuteStep={5}
                                    disabled={!form.getFieldValue('interviewDate')}
                                    format="HH:mm"
                                    placeholder="请选择结束时间"
                                    style={{ width: '100%' }}
                                    onChange={v => handleCheck(v, 'interviewStartTime')}
                                    onOpenChange={v => handleOpenChange(v, 'interviewEndTime')}
                                />
                            )}
                        </Form.Item>
                    </div>
                </Form.Item>
                {!isAddPage && !!query?.type && timeList && timeList.length > 0 && (
                    <Form.Item label=" " colon={false}>
                        <div style={{ lineHeight: 1, paddingBottom: 6 }}>候选人提供的时间段如下：</div>
                        {timeList?.map(item => (
                            <div key={item.startTime}>
                                <Button type="dashed" onClick={() => handleTimeClick(item)}>
                                    {moment(item.startTime).format('YYYY-MM-DD HH:mm')}
                                    {moment(item.endTime).format('-HH:mm')}
                                </Button>
                            </div>
                        ))}
                    </Form.Item>
                )}
            </>
        );
        return view;
    };
    const interWayListView = () => {
        const interVal = getPath(arrangeDetailVO, 'interviewWay', undefined);
        if (!interVal) {
            return (
                <Select
                    placeholder="请选择面试方式"
                    allowClear
                    getPopupContainer={triggerNode => triggerNode.parentElement}
                >
                    {renderOptions(interviewWayList)}
                </Select>
            );
        }
        if (interVal === INTERVIEWWAY.WORK) {
            return (
                <Select
                    placeholder="请选择面试方式"
                    allowClear
                    disabled
                    getPopupContainer={triggerNode => triggerNode.parentElement}
                >
                    {renderOptions(interviewWayList)}
                </Select>
            );
        }
        return (
            <Select
                placeholder="请选择面试方式"
                allowClear
                getPopupContainer={triggerNode => triggerNode.parentElement}
            >
                {renderOptions(interviewWayList.filter(m => m.value !== INTERVIEWWAY.WORK))}
            </Select>
        );
    };

    const [wayLabel, wayDetail, wayField] = useInterviewWay({
        interviewWay: interviewWayResult || arrangeDetailVO?.interviewWay,
        interviewLocation: arrangeDetailVO?.interviewLocation,
        videoLink: arrangeDetailVO?.videoLink
    });

    const arrangeForm = (
        <>
            {contactResult === RESULT.ACCEPT && (
                <>
                    <FormHeader title="面试安排" style={{ marginBottom: 24 }} />
                    <Form className={styles.formWrap}>
                        {infoVisible && (
                            <Form.Item
                                label={
                                    interviewRoundList.find(item => item.value === arrangeDetailVO?.interviewRound)
                                        ?.label
                                }
                                style={{ marginBottom: 0 }}
                                className={styles.formEditWrap}
                            >
                                {interviewWayList.find(item => item.value === arrangeDetailVO?.interviewWay)?.label}
                                <>&nbsp;-&nbsp;{wayDetail}</>
                                <div className={styles.formEdit}>
                                    <Icon
                                        title="编辑"
                                        type="listfunction_edit_icon_default"
                                        onClick={() => setInfoVisible(false)}
                                    />
                                </div>
                            </Form.Item>
                        )}
                        <div style={{ display: infoVisible ? 'none' : 'flex' }}>
                            <Form.Item label="面试轮次" style={{ width: '50%' }}>
                                <Spin spinning={roundLoading}>
                                    {getFieldDecorator('interviewRound', {
                                        initialValue: getPath(arrangeDetailVO, 'interviewRound', undefined),
                                        rules: [
                                            {
                                                required: true,
                                                message: '面试轮次不能为空'
                                            }
                                        ]
                                    })(
                                        <Select
                                            placeholder="请选择面试轮次"
                                            allowClear
                                            getPopupContainer={triggerNode => triggerNode.parentElement}
                                        >
                                            {renderOptions(interviewRoundList)}
                                        </Select>
                                    )}
                                </Spin>
                            </Form.Item>
                            <Form.Item label="面试方式" style={{ width: '50%' }}>
                                {getFieldDecorator('interviewWay', {
                                    initialValue: getPath(arrangeDetailVO, 'interviewWay', undefined),
                                    rules: [
                                        {
                                            required: true,
                                            message: '面试方式不能为空'
                                        }
                                    ]
                                })(interWayListView())}
                            </Form.Item>
                        </div>
                        {interviewWayResult !== INTERVIEWWAY.WORK && (
                            <Form.Item
                                label={wayLabel}
                                style={{
                                    display: infoVisible ? 'none' : 'flex',
                                    marginBottom: employeeVisible ? 8 : ''
                                }}
                            >
                                {getFieldDecorator(wayField, {
                                    initialValue: getPath(arrangeDetailVO, wayField, ''),
                                    rules: [
                                        {
                                            required: form.getFieldValue('interviewWay') === 1,
                                            message: `请输入${wayLabel}`
                                        }
                                    ]
                                })(<Input placeholder={`请输入${wayLabel}`} allowClear maxLength={100} />)}
                            </Form.Item>
                        )}
                        {employeeVisible && (
                            <Form.Item label="面试官" style={{ marginBottom: 8 }} className={styles.formEditWrap}>
                                {getPath(arrangeDetailVO, 'interviewEmployees', [])
                                    .map(item => item.employeeName)
                                    .join('、')}
                                <div className={styles.formEdit}>
                                    <Icon
                                        title="编辑"
                                        type="listfunction_edit_icon_default"
                                        onClick={() => setEmployeeVisible(false)}
                                    />
                                </div>
                            </Form.Item>
                        )}
                        <Form.Item label="面试官" style={{ display: employeeVisible ? 'none' : 'flex' }}>
                            {getFieldDecorator('interviewEmployeeCodeList', {
                                initialValue: isAddPage
                                    ? getInterviewEmployees()
                                    : getPath(arrangeDetailVO, 'interviewEmployees', []).map(item => item.employeeCode),
                                rules: [
                                    {
                                        required: true,
                                        message: '面试官不能为空'
                                    }
                                ]
                            })(
                                <Select
                                    mode="multiple"
                                    style={{ width: '100%' }}
                                    placeholder="请选择面试官"
                                    allowClear
                                    getPopupContainer={triggerNode => triggerNode.parentElement}
                                    onFocus={handleEmployeeFocus}
                                    onSearch={handleSearch}
                                    filterOption={false}
                                >
                                    {employeeList?.map(item => (
                                        <Option value={item.employeeCode} key={item.employeeCode}>
                                            {item.employeeName}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                        {interviewWayResult === INTERVIEWWAY.WORK ? getInterViewWorkView() : getNotInterViewWorkView()}
                    </Form>
                    {interviewWayResult !== INTERVIEWWAY.WORK && (
                        <Form className={styles.formWrap2}>
                            <Form.Item label="面试官日程">
                                {getFieldDecorator('schedule', {
                                    rules: [
                                        {
                                            validator(rule, value, callback) {
                                                if (!value) {
                                                    callback('日程有冲突');
                                                } else {
                                                    callback();
                                                }
                                            }
                                        }
                                    ]
                                })(
                                    <Schedule
                                        rangeTitle="我的标题"
                                        date={form.getFieldValue('interviewDate')}
                                        timeRange={[
                                            form.getFieldValue('interviewStartTime'),
                                            form.getFieldValue('interviewEndTime')
                                        ]}
                                        onRangeChange={nextTimeRange => {
                                            const [startTime, endTime] = nextTimeRange;
                                            form.setFieldsValue({
                                                interviewDate: moment(startTime),
                                                interviewStartTime: moment(startTime),
                                                interviewEndTime: moment(endTime)
                                            });
                                        }}
                                        excludeInterviewCodes={[getPath(arrangeDetailVO, 'interviewArrangeCode')]}
                                        employeeCodes={form.getFieldValue('interviewEmployeeCodeList') || []}
                                        height={400}
                                    />
                                )}
                            </Form.Item>
                        </Form>
                    )}

                    <Form className={styles.formWrap}>
                        <Form.Item label="邮件通知候选人">
                            {getFieldDecorator('candidateNoticeStatus', {
                                initialValue: getPath(
                                    arrangeDetailVO,
                                    'candidateNoticeStatus',
                                    checkCode('office:recruitment:course:notice') ? 1 : 0
                                ),
                                rules: [
                                    {
                                        required: true,
                                        message: '通知候选人不能为空'
                                    }
                                ]
                            })(
                                <Radio.Group>
                                    {checkCode('office:recruitment:course:notice') && (
                                        <Radio
                                            value={1}
                                            key={1}
                                            style={{ display: 'block', height: 40, lineHeight: '40px' }}
                                        >
                                            是
                                        </Radio>
                                    )}
                                    <Radio
                                        value={0}
                                        key={0}
                                        disabled={interviewWayResult === INTERVIEWWAY.WORK || isNeedSendMail}
                                    >
                                        <span style={{ marginRight: 8 }}>否</span>
                                        {form.getFieldValue('candidateNoticeStatus') === 1 && (
                                            <>
                                                <Checkbox disabled>候选人已到场</Checkbox>
                                            </>
                                        )}
                                        {form.getFieldValue('candidateNoticeStatus') === 0 && (
                                            <>
                                                {getFieldDecorator('candidatePresentStatus', {
                                                    initialValue: !!getPath(
                                                        arrangeDetailVO,
                                                        'candidatePresentStatus',
                                                        false
                                                    ),
                                                    valuePropName: 'checked'
                                                })(<Checkbox>候选人已到场</Checkbox>)}
                                            </>
                                        )}
                                    </Radio>
                                </Radio.Group>
                            )}
                            <div style={{ lineHeight: 1, color: 'rgba(0,0,0,.25)' }}>
                                {form.getFieldValue('candidateNoticeStatus') === 1
                                    ? '面试安排确定后，将打开通知候选人页面'
                                    : '后续可在候选列表另行通知'}
                            </div>
                        </Form.Item>
                    </Form>
                </>
            )}
        </>
    );

    const getAlert = flag => {
        if (flag) {
            return (
                <Alert
                    message="该候选人有未完成的面试安排，如果淘汰将自动取消"
                    type="warning"
                    style={{ marginBottom: 24 }}
                    showIcon
                    closable
                />
            );
        }
        return null;
    };
    const resetErrTip = () => {
        form.resetFields(['contactDesc']);
    };
    return (
        <PageHeaderWrapper>
            <Card
                title={isAddPage ? '联系面试' : '修改面试'}
                bordered={false}
                loading={talentLoading || loading}
                extra={
                    <BottomAction>
                        {!isAddPage && !query?.type && (
                            <AuthComponent code="office:recruitment:course:interview:undo">
                                <Button type="danger" ghost onClick={() => modalRef.current.show()}>
                                    撤销面试
                                </Button>
                            </AuthComponent>
                        )}
                        <Button onClick={() => pageTabUtil.goBack()}>取消</Button>
                        <Button
                            type="primary"
                            onClick={handleSubmit}
                            loading={submitLoading}
                            disabled={
                                !isAddPage &&
                                ![1, 2, 8, 9, 10].includes(getPath(arrangeDetailVO, 'interviewStatus', ''))
                            }
                        >
                            确定
                        </Button>
                    </BottomAction>
                }
            >
                <TalentInfoHead talent={talentInfo || {}} />
                <Divider />
                {isAddPage && (
                    <>
                        {getAlert(contactResult === RESULT.RECOMMEND && currentPositionFlag && processStatus?.hintType)}
                        {getAlert(contactResult === RESULT.OUT && processStatus?.hintType)}
                        <FormHeader title="联系记录" />
                        <Form className={styles.formWrap}>
                            <Form.Item label="联系方式">
                                {getFieldDecorator('contactWay', {
                                    initialValue: 1,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择联系方式'
                                        }
                                    ]
                                })(
                                    <Select
                                        placeholder="请选择联系方式的类型"
                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                    >
                                        {renderOptions(contactWayList)}
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item
                                label={
                                    contactWayList.find(item => item.value === form.getFieldValue('contactWay'))?.title
                                }
                            >
                                {getFieldDecorator('contactInfo', {
                                    initialValue: getPath(info, 'contactInfo', '')
                                })(
                                    <Input
                                        placeholder={`请输入${
                                            contactWayList.find(item => item.value === form.getFieldValue('contactWay'))
                                                ?.title
                                        }`}
                                        allowClear
                                        maxLength={50}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item label="联系时间">
                                {getFieldDecorator('contactTime', {
                                    initialValue: moment(),
                                    rules: [
                                        {
                                            required: true,
                                            message: '联系时间不能为空'
                                        }
                                    ]
                                })(
                                    <DatePicker
                                        showTime={{ format: 'HH:mm' }}
                                        format="YYYY-MM-DD HH:mm"
                                        placeholder="请选择联系时间"
                                        style={{ width: '100%' }}
                                        disabled
                                    />
                                )}
                            </Form.Item>
                            <Form.Item label="联系结果">
                                {getFieldDecorator('contactResult', {
                                    initialValue: getPath(contactRecordDetailVO, 'contactResult', 1),
                                    rules: [
                                        {
                                            required: true,
                                            message: '联系结果不能为空'
                                        }
                                    ]
                                })(
                                    <Radio.Group>
                                        {resultTypeList.map(item => (
                                            <Radio value={item.value} key={item.value} onChange={() => resetErrTip()}>
                                                {item.label}
                                            </Radio>
                                        ))}
                                    </Radio.Group>
                                )}
                            </Form.Item>
                            {contactResult === RESULT.ACCEPT && (
                                <Form.Item label="联系内容">
                                    {getFieldDecorator('contactDesc', {
                                        initialValue: '',
                                        rules: [
                                            {
                                                required: true,
                                                message: '联系内容不能为空'
                                            }
                                        ]
                                    })(
                                        <TextArea
                                            placeholder="请输入联系内容"
                                            autoSize={{ minRows: 3, maxRows: 6 }}
                                            maxLength={800}
                                        />
                                    )}
                                </Form.Item>
                            )}
                            {contactResult === RESULT.RECOMMEND && (
                                <>
                                    <Form.Item label="推荐岗位">
                                        <div style={{ display: 'flex' }}>
                                            <div style={{ flex: 1, maxWidth: '100%' }}>
                                                <Spin spinning={postLoading}>
                                                    {getFieldDecorator('recommendRecruitId', {
                                                        initialValue: getPath(info, 'recommendRecruitId', undefined),
                                                        rules: [
                                                            {
                                                                required: true,
                                                                message: '推荐岗位不能为空'
                                                            },
                                                            {
                                                                validator: (rule, value, callback) => {
                                                                    if (!value || !postList?.length) {
                                                                        return callback();
                                                                    }
                                                                    const flag = postList.find(
                                                                        item => item?.recruitId === value
                                                                    )?.existState;
                                                                    if (flag) {
                                                                        return callback(
                                                                            '当前候选人已应聘此招聘岗位，请勿重复推荐'
                                                                        );
                                                                    }
                                                                    return callback();
                                                                }
                                                            }
                                                        ]
                                                    })(
                                                        <Select
                                                            showSearch
                                                            style={{ width: '100%' }}
                                                            placeholder="请选择推荐岗位 - 部门（招聘负责人）"
                                                            getPopupContainer={triggerNode => triggerNode.parentElement}
                                                            optionFilterProp="label"
                                                            dropdownMatchSelectWidth={false}
                                                            dropdownStyle={{ maxWidth: 500 }}
                                                        >
                                                            {postList?.map(item => (
                                                                <Option
                                                                    value={item.recruitId}
                                                                    key={item.recruitId}
                                                                    label={item.name}
                                                                >
                                                                    {`${item.name}（${item.principalEmployeeName ||
                                                                        '--'}）`}
                                                                </Option>
                                                            ))}
                                                        </Select>
                                                    )}
                                                </Spin>
                                            </div>
                                            <div style={{ height: 40, marginLeft: 24 }}>
                                                {getFieldDecorator('currentPositionEliminateFlag', {
                                                    initialValue: true,
                                                    valuePropName: 'checked'
                                                })(
                                                    <Checkbox onChange={handlePositionFlagChange}>
                                                        从当前应聘岗位中淘汰
                                                    </Checkbox>
                                                )}
                                            </div>
                                        </div>
                                    </Form.Item>
                                    <Form.Item label="通知人员">
                                        {getFieldDecorator('noticeEmployeeCodeList', {
                                            initialValue: undefined
                                        })(
                                            <Select
                                                mode="multiple"
                                                style={{ width: '100%' }}
                                                placeholder="请选择通知人员"
                                                allowClear
                                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                                onFocus={handleEmployeeFocus}
                                                onSearch={handleSearch}
                                                filterOption={false}
                                            >
                                                {employeeList?.map(item => (
                                                    <Option
                                                        value={item.employeeCode}
                                                        key={item.employeeCode}
                                                        disabled={recommendDisabled?.includes(item.employeeCode)}
                                                    >
                                                        {item.employeeName}
                                                    </Option>
                                                ))}
                                            </Select>
                                        )}
                                    </Form.Item>
                                    <Form.Item label="理由">
                                        {getFieldDecorator('contactDesc', {
                                            initialValue: '',
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '理由不能为空'
                                                }
                                            ]
                                        })(
                                            <TextArea
                                                placeholder="请输入理由"
                                                autoSize={{ minRows: 3, maxRows: 6 }}
                                                maxLength={800}
                                            />
                                        )}
                                    </Form.Item>
                                </>
                            )}
                            {contactResult === RESULT.OUT && (
                                <Form.Item label="理由">
                                    {getFieldDecorator('contactDesc', {
                                        initialValue: '',
                                        rules: [
                                            {
                                                required: true,
                                                message: '理由不能为空'
                                            }
                                        ]
                                    })(
                                        <TextArea
                                            placeholder="请输入理由"
                                            autoSize={{ minRows: 3, maxRows: 6 }}
                                            maxLength={800}
                                        />
                                    )}
                                </Form.Item>
                            )}
                            {contactResult === RESULT.OTHER && (
                                <Form.Item label="备注">
                                    {getFieldDecorator('contactDesc', {
                                        initialValue: '',
                                        rules: [
                                            {
                                                required: true,
                                                message: '备注不能为空'
                                            }
                                        ]
                                    })(
                                        <TextArea
                                            placeholder="请输入备注"
                                            autoSize={{ minRows: 3, maxRows: 6 }}
                                            maxLength={800}
                                        />
                                    )}
                                </Form.Item>
                            )}
                        </Form>
                        <Divider />
                        {arrangeForm}
                    </>
                )}

                {!isAddPage && (
                    <>
                        {arrangeForm}
                        <Divider />
                        <div style={{ position: 'relative' }}>
                            <FormHeader title="联系记录" />
                            <a
                                style={{
                                    position: 'absolute',
                                    right: 0,
                                    top: 0
                                }}
                                onClick={e => {
                                    e.preventDefault();
                                    setVisible(!visible);
                                }}
                            >
                                {visible ? '收起' : '展开'}
                            </a>
                        </div>
                        {visible && <InviteDetail dataSource={inviteList} keyStyle={{ width: 140 }} />}
                    </>
                )}
            </Card>
            {!isAddPage && !query?.type && <RevokeModal wrappedComponentRef={modalRef} arrangeId={arrangeId} />}
        </PageHeaderWrapper>
    );
};

// export default connect(({ user }) => ({ user: user.currentUser }))(Form.create({})(Invite));
export default Form.create({})(Invite);
